import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class EditEmpForm extends JFrame { 
	private static final long serialVersionUID = 1L;
	JPanel edPanel;
	private JLabel fname, mname, lname, curpass, newpass, newpass1, bDate, adDr, contactNo;
	private JTextField firstName, middleName, lastName, cPass, nPass, nPass1, contactNum, oldPass;
	private JComboBox bMonth,Bday,Byear;
	private JTextArea address;
	private JButton submit, cancel;
	ImageIcon ii = new ImageIcon(this.getClass().getResource("images/editprofilebg.png"));
	private Image bgImage = ii.getImage();
	String[] bMonthItems = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	int[] intDay = new int[31];
	String[] BdayItems = new String[31];
	int[] intYear = new int[54];
	String ByearItems[] = new String[54];

	Connection conn = null;
	PreparedStatement pstmt = null;

	public EditEmpForm() {

		setTitle("Edit Profile");

		edPanel =  new JPanel() {
			private static final long serialVersionUID = 1L;

			protected void paintComponent(Graphics g){
				g.drawImage(bgImage, 0, 0, null);
				super.paintComponent(g);
			}
		};

		//construct components
		fname = new JLabel ("* First Name:");
		mname = new JLabel ("* Middle Initial:");
		lname = new JLabel ("* Last Name:");
		firstName = new JTextField (5);
		middleName = new JTextField (5);
		lastName = new JTextField (5);
		curpass = new JLabel ("* Current Password:");
		newpass = new JLabel ("New Password:");
		newpass1 = new JLabel ("Confirm New Password:");
		cPass = new JTextField(5);
		nPass = new JTextField(5);
		nPass1 = new JTextField(5);
		oldPass = new JTextField(5);
		bDate = new JLabel ("Birthdate:");
		bMonth = new JComboBox (bMonthItems);
		Bday = new JComboBox ();
		Byear = new JComboBox ();
		adDr = new JLabel ("* Address:");
		address = new JTextArea (5, 5);
		contactNo = new JLabel ("* Contact No.:");
		contactNum = new JTextField (5);
		submit = new JButton ("Save Changes");
		cancel = new JButton ("Cancel");

		InitializeDrop(new Integer(31));
		InitializeYear();

		//set components properties
		bMonth.setToolTipText ("Month");
		Bday.setToolTipText ("Day");
		Byear.setToolTipText ("Year");

		//adjust size and set layout
		setPreferredSize (new Dimension (319, 428));
		setLayout (null);
		setResizable(false);

		//add components
		edPanel.add (fname);
		edPanel.add (mname);
		edPanel.add (lname);
		edPanel.add (curpass);
		edPanel.add (newpass);
		edPanel.add (newpass1);
		edPanel.add (bDate);
		edPanel.add (adDr);
		edPanel.add (contactNo);

		edPanel.add (firstName);
		edPanel.add (middleName);
		edPanel.add (lastName);
		edPanel.add (cPass);
		edPanel.add (nPass);
		edPanel.add (nPass1);
		edPanel.add (contactNum);
		edPanel.add (address);

		edPanel.add (bMonth);
		edPanel.add (Bday);
		edPanel.add (Byear);

		edPanel.add (submit);
		edPanel.add (cancel);

		add(edPanel);

		edPanel.setSize(319,428);
		edPanel.setOpaque(false);
		edPanel.setLayout(null);
		edPanel.setVisible(true);

		//set component bounds (only needed by Absolute Positioning)

		fname.setBounds (14, 85, 85, 25);
		mname.setBounds (14, 110, 85, 25);
		lname.setBounds (14, 135, 85, 25);

		firstName.setBounds (160, 85, 120, 25);
		middleName.setBounds (160, 110, 120, 25);
		lastName.setBounds (160, 135, 120, 25);

		curpass.setBounds (14, 160, 115, 25);
		newpass.setBounds (15, 185, 95, 25);
		newpass1.setBounds (15, 210, 145, 25);

		cPass.setBounds (160, 160, 120, 25);
		nPass.setBounds (160, 185, 120, 25);
		nPass1.setBounds (160, 210, 120, 25);

		adDr.setBounds (14, 270, 80, 25);
		address.setBounds (120, 275, 160, 60);

		contactNo.setBounds (14, 335, 80, 25);
		contactNum.setBounds (120, 335, 100, 25);

		bDate.setBounds (15, 240, 60, 25);
		bMonth.setBounds (70, 240, 90, 25);
		Bday.setBounds (165, 240, 60, 25);
		Byear.setBounds (230, 240, 80, 25);

		submit.setBounds (85, 370, 110, 25);
		cancel.setBounds (195, 370, 100, 25);

		fname.setForeground(Color.WHITE);
		mname.setForeground(Color.WHITE);
		lname.setForeground(Color.WHITE);
		curpass.setForeground(Color.WHITE);
		newpass.setForeground(Color.WHITE);
		newpass1.setForeground(Color.WHITE);
		bDate.setForeground(Color.WHITE);
		adDr.setForeground(Color.WHITE);
		contactNo.setForeground(Color.WHITE);
		submit.setForeground(Color.WHITE);
		cancel.setForeground(Color.WHITE);
		submit.setBackground(Color.BLACK);
		cancel.setBackground(Color.BLACK);

		try
		{

			ConnectionFactory myFactory = ConnectionFactory.getFactory();
			Connection conn = myFactory.getConnection();
			Statement stat = conn.createStatement();

			ResultSet res = stat.executeQuery("SELECT firstName, middleInitial, lastName, bDate, password, contactNum, address FROM bernalcompany.employee WHERE idemployee ="+MainPanel.getUID());

			if(res.next()){

				oldPass.setText(res.getString("password"));
				firstName.setText(res.getString("firstName"));
				middleName.setText(res.getString("middleInitial"));
				lastName.setText(res.getString("lastName"));

				String[] dates = res.getDate("bDate").toString().split("-");
				bMonth.setSelectedIndex(Integer.parseInt(dates[1])-1);
				Bday.setSelectedIndex((Integer.parseInt(dates[2])-1));
				Byear.setSelectedItem((Object)(dates[0]));

				contactNum.setText(res.getString("contactNum"));
				address.setLineWrap(true);
				address.setText(res.getString("address"));
				address.setWrapStyleWord(true);
				address.setEditable(true);

			}

			conn.close();

		}catch(Exception ex){
			ex.printStackTrace();
		} 

		cancel.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				setVisible(false);
				AdminForm.goToPage(1);
			}
		});

		submit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){

				try
				{
					String bday = getByear() + "-" + getbMonth() + "-" + getBday();

					if ( getFirstName().length() == 0 || getMiddleName().length() == 0 || getLastName().length() == 0 || getPassword().length() == 0 || getAddress().length() == 0 || getContactNum().length() == 0 )
						JOptionPane.showMessageDialog(edPanel, "Fields with * must not be left blank.", "Error", JOptionPane.ERROR_MESSAGE);
					else {				

						if ( getNewPassword().length() == 0 && getConfirmPassword().length() == 0 ) {

							if ( getPassword().equals(getOldPassword()) ) {

								JDialog.setDefaultLookAndFeelDecorated(true);
								int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to save changes to your profile?", "CONFIRM CHANGES", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

								if(response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION){
									setVisible(true);
								}
								else
									if(response == JOptionPane.YES_OPTION){

										ConnectionFactory myFactory = ConnectionFactory.getFactory();
										Connection conn = myFactory.getConnection();

										PreparedStatement pstmt;

										pstmt = conn.prepareStatement("UPDATE bernalcompany.employee" +
												"					   SET firstName = ?" +
														"						 , middleInitial = ?" +
														"						 , lastName = ?" +
														"						 , bDate = ?" +
														"						 , password = ?" +
														"						 , contactNum = ?" +
														"						 , address = ?" +
														"	   				   WHERE idemployee = '"+MainPanel.getUID()+"'");

										pstmt.setString(1, getFirstName());
										pstmt.setString(2, getMiddleName());
										pstmt.setString(3, getLastName());
										pstmt.setString(4, bday);
										pstmt.setString(5, getPassword());
										pstmt.setString(6, getContactNum());
										pstmt.setString(7, getAddress());

										pstmt.executeUpdate();
										pstmt.close();


										System.out.println("PASSWORD: ");
										System.out.println(getPassword());


										setVisible(false);
										JOptionPane.showMessageDialog(edPanel, "You have successfully edited your profile.");
										AdminForm.goToPage(1);

									}           			   	

							}
							else
								JOptionPane.showMessageDialog(edPanel, "Incorrect Password.", "Error", JOptionPane.ERROR_MESSAGE);

						}
						else if ( ( getNewPassword().length() == 0 && getConfirmPassword().length() > 0 ) || ( getNewPassword().length() > 0 && getConfirmPassword().length() == 0 ) )

							JOptionPane.showMessageDialog(edPanel, "Confirm new password first!", "Error", JOptionPane.ERROR_MESSAGE);

						else if ( ( getNewPassword().length() > 0 && getConfirmPassword().length() > 0 ) && getNewPassword().equals(getConfirmPassword()) && getPassword().equals(getOldPassword())) {

							JDialog.setDefaultLookAndFeelDecorated(true);
							int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to save changes to your profile?", "CONFIRM CHANGES", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
							if(response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION){
								setVisible(true);
							}
							else
								if(response == JOptionPane.YES_OPTION){

									ConnectionFactory myFactory = ConnectionFactory.getFactory();
									Connection conn = myFactory.getConnection();

									PreparedStatement pstmt;

									pstmt = conn.prepareStatement("UPDATE bernalcompany.employee" +
											"					   SET firstName = ?" +
													"						 , middleInitial = ?" +
													"						 , lastName = ?" +
													"						 , password = ?" +
													"						 , bDate = ?" +
													"						 , contactNum = ?" +
													"						 , address = ?" +
													"	   				   WHERE idemployee = '"+MainPanel.getUID()+"'");

									pstmt.setString(1, getFirstName());
									pstmt.setString(2, getMiddleName());
									pstmt.setString(3, getLastName());
									pstmt.setString(4, getConfirmPassword());
									pstmt.setString(5, bday);
									pstmt.setString(6, getContactNum());
									pstmt.setString(7, getAddress());

									pstmt.executeUpdate();
									pstmt.close();

									System.out.println("CONFIRM PASSWORD: ");
									System.out.println(getConfirmPassword());

									setVisible(false);
									JOptionPane.showMessageDialog(edPanel, "You have successfully edited your profile.");
									AdminForm.goToPage(1);  
								}    

						}
						else
							JOptionPane.showMessageDialog(edPanel, "Passwords does not match.", "Error", JOptionPane.ERROR_MESSAGE);
					}		

				} catch(Exception ex){
					ex.printStackTrace();
				}
			}
		});


		bMonth.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent e){

				boolean leap = false;

				leap = CheckLeap(Integer.parseInt(Byear.getSelectedItem().toString()));

				if(bMonth.getSelectedIndex() == 1)
				{
					if(leap==false)
						InitializeDrop(28);
					else
						InitializeDrop(29); 
				}
				else if (bMonth.getSelectedIndex() == 0 || bMonth.getSelectedIndex() == 2 || bMonth.getSelectedIndex() == 4 
						|| bMonth.getSelectedIndex() == 6 || bMonth.getSelectedIndex() == 7 || bMonth.getSelectedIndex() == 9
						|| bMonth.getSelectedIndex() == 11)
					InitializeDrop(31);
				else if (bMonth.getSelectedIndex() == 3 || bMonth.getSelectedIndex() == 5 || bMonth.getSelectedIndex() == 8
						|| bMonth.getSelectedIndex() == 10)
					InitializeDrop(30);
			}
		}
		);

		Byear.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent e){

				boolean leap = false;

				leap = CheckLeap(Integer.parseInt(Byear.getSelectedItem().toString()));

				if(bMonth.getSelectedIndex() == 1)
				{
					if(leap==false)
						InitializeDrop(28);
					else
						InitializeDrop(29); 
				}
			}
		}
		);

	}

	public void InitializeDrop(int ctr) {

		Bday.removeAllItems();

		for(int a = 1; a <= ctr; a++ )
		{     
			intDay[a-1] = a;
			BdayItems[a-1] = Integer.toString(intDay[a-1]);
			Bday.addItem(BdayItems[a-1]);
		}

		Bday.repaint();


	}

	public void InitializeYear() {

		for(int a = 1940; a <= 1993; a++)
		{     
			int index = 0;
			intYear[index] = a;
			ByearItems[index] = Integer.toString(intYear[index]);
			Byear.addItem(ByearItems[index]);
			index++;
		}

	}

	public boolean CheckLeap(int year) {
		if(year%4 == 0)
		{
			if(year%100 != 0)
			{
				return true;
			}
			else
			{
				if(year%400 == 0)
					return true;
				else
					return false;
			}
		}
		return false;
	}

	public String getFirstName() {
		return firstName.getText().trim();
	}

	public String getMiddleName() {
		return middleName.getText().trim();
	}

	public String getLastName() {
		return lastName.getText().trim();
	}

	public String getContactNum() {
		return contactNum.getText().trim();
	}

	public String getOldPassword() {
		return oldPass.getText().trim();
	}

	public String getPassword() {
		return cPass.getText().trim();
	}

	public String getNewPassword() {
		return new String(nPass.getText().trim());
	}

	public String getConfirmPassword() {
		return new String(nPass1.getText().trim());
	}

	public String getAddress() {
		return address.getText().trim();
	}

	public int getbMonth() {
		String mon = bMonth.getSelectedItem().toString();
		int con = 0;
		if(mon.equals("January"))
			con = 1;
		else if(mon.equals("February"))
			con = 2;
		else if(mon.equals("March"))
			con = 3;
		else if(mon.equals("April"))
			con = 4;
		else if(mon.equals("May"))
			con = 5;
		else if(mon.equals("June"))
			con = 6;
		else if(mon.equals("July"))
			con = 7;
		else if(mon.equals("August"))
			con = 8;
		else if(mon.equals("September"))
			con = 9;
		else if(mon.equals("October"))
			con = 10;
		else if(mon.equals("November"))
			con = 11;
		else
			con = 12;

		return con;
	}

	public String getBday() {
		return Bday.getSelectedItem().toString();
	}

	public String getByear() {
		return Byear.getSelectedItem().toString();
	}

}
